//
//  PPTimelineDetailHeaderView.m
//  pickpic
//
//  Created by GaoYongyue on 16/9/25.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPTimelineDetailHeaderView.h"
#import "PPProfileViewController.h"
#import "PPTimelineLikesViewController.h"
#import "PPTimelineFavouritesViewController.h"
#import "PPCommentTimelineViewController.h"
#import "PPFriendsTimelineCellMoreActionSheet.h"
#import "PPComplainViewController.h"
#import "PPTimelinePictureViewController.h"

#import "PPActivityCommitManager.h"
#import "PPProfileMoreActionSheet.h"

#import "PPPictureLoadingProgressView.h"

@interface PPTimelineDetailHeaderView ()
@property (weak, nonatomic) IBOutlet UIImageView *avatarView;
@property (weak, nonatomic) IBOutlet UILabel *nickLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *coverViewHeight;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;

@property (weak, nonatomic) IBOutlet UIView *coverBottomMaskView;
@property (weak, nonatomic) IBOutlet UILabel *coverNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *coverCountLabel;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *descLabelTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *descLabelHeight;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet DGAlignmentButton *likeCountButton;
@property (weak, nonatomic) IBOutlet DGAlignmentButton *favouriteCountButton;
@property (weak, nonatomic) IBOutlet UIButton *likeButton;

@property (weak, nonatomic) IBOutlet UIButton *favouriteButton;
@property (weak, nonatomic) IBOutlet UIButton *likeCountButton2;

@property (readwrite, nonatomic, strong) PPPictureLoadingProgressView *progressView;
@end

@implementation PPTimelineDetailHeaderView

- (void)awakeFromNib {
    [super awakeFromNib];
    _avatarView.layer.masksToBounds = YES;
    _avatarView.layer.cornerRadius = 18.f;

    __weak typeof(self)weakSelf = self;
    [_avatarView setActionBlock:^(UIControl *control) {
        [weakSelf portraitDidPress];
    } forEvent:UIControlEventTouchUpInside];

    [_nickLabel setActionBlock:^(UIControl *control) {
        [weakSelf portraitDidPress];
    } forEvent:UIControlEventTouchUpInside];

    _coverImageView.clipsToBounds = YES;
    
    [_coverImageView setActionBlock:^(UIControl *control) {
        [MobClick event:@"107"];
        PPAlbumObject *album = weakSelf.album;

        if(album.pictures.count == 0) {
            [weakSelf.delegateViewController.navigationController.view toastMessage:@"图册暂时还没有图片哦"];
            return;
        }

        PPTimelinePictureViewController *pictureViewController = [[PPTimelinePictureViewController alloc] init];
        pictureViewController.pictures = album.pictures;
        pictureViewController.ownerID = album.userID;
        pictureViewController.albumTitle = album.title;
        [weakSelf.delegateViewController.navigationController pushViewController:pictureViewController animated:YES];
    } forEvent:UIControlEventTouchUpInside];

    _progressView = [[PPPictureLoadingProgressView alloc] init];
    _progressView.trackColor = [UIColor colorWithRGBHex:0xd9d9d9];
    _progressView.valueColor = [UIColor colorWithRGBHex:0xc5c5c5];
    [_coverImageView addSubview:_progressView];

    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(60));
        make.height.equalTo(@(60));
        make.center.equalTo(_coverImageView);
    }];
}

- (void)portraitDidPress {
    [MobClick event:@"103"];
    PPProfileViewController *vc = [[PPProfileViewController alloc] init];
    vc.userID = _album.userID;
    [_delegateViewController.navigationController pushViewController:vc animated:YES];
}

- (void)setAlbum:(PPAlbumObject *)album {
    _album = album;

    _progressView.hidden = YES;

    // avatar
    {
        if(album.ownerAvatar.length > 0) {
            [album.ownerAvatar applyToImageView:_avatarView];
        } else {
            _avatarView.image = [UIImage imageNamed:@"icon-person-70"];
        }
    }


    // nick
    {
        _nickLabel.text = album.ownerName;
    }

    // date
    {
        _dateLabel.text = [album.createDate timeAgoForTimeline];
    }

    // audit
    {
        if(album.audit == 2) {
            _coverImageView.image = [UIImage imageNamed:@"ban-2"];
            _coverImageView.contentMode = UIViewContentModeCenter;
        } else {
            _coverImageView.contentMode = UIViewContentModeScaleAspectFill;

            __weak typeof(self) weakSelf = self;

            NSString *URLString = album.existingCoverURLString;

            if(URLString.length > 0) {
                weakSelf.progressView.hidden = NO;

                [URLString applyToImageView:_coverImageView placeholder:nil progressive:^(double progress) {
                    weakSelf.progressView.progress = progress;
                } completion:^{
                    weakSelf.progressView.hidden = YES;
                }];
            }
        }
    }

    _coverViewHeight.constant = [UIScreen mainScreen].bounds.size.width;

    // title
    {
        _coverNameLabel.text = album.title;

        _coverCountLabel.text = [NSString stringWithFormat:@"%ld张", (long)album.pictures.count];
    }

    NSString *description = album.desc;

    _descLabel.attributedText = [[NSAttributedString alloc] initWithString:description attributes:[self class].attributes];

    CGSize constrainedSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 2*15, CGFLOAT_MAX);

    _descLabel.width = constrainedSize.width;
    [_descLabel sizeToFit];

    if([description length] == 0)
    {
        _descLabelTop.constant = 0;
    }
    else
    {
        _descLabelTop.constant = 8;
    }

    _likeButton.selected = album.isLiked;
    _favouriteButton.selected = album.isFavorited;

    [_likeCountButton setTitle:[NSString stringWithFormat:@"%ld", album.like] forState:UIControlStateNormal];
    [_likeCountButton2 setTitle:[NSString stringWithFormat:@"%ld", album.like] forState:UIControlStateNormal];

    [_favouriteCountButton setTitle:[NSString stringWithFormat:@"%ld", album.favorite] forState:UIControlStateNormal];
    _favouriteCountButton.hidden = album.favorite > 0 ? NO : YES;
    _likeCountButton2.hidden = (album.like > 0 && _favouriteCountButton.hidden == YES) ? NO  : YES;
    _likeCountButton.hidden = (album.like > 0 && _likeCountButton2.hidden == YES) ? NO  : YES;
}

- (IBAction)moreButtonDidPress:(id)sender {

    [MobClick event:@"104"];
    if ([_album.userID isEqualToString:DGCurrentAccount.userID])
    {
        PPProfileMoreActionSheet *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPProfileMoreActionSheet" owner:nil options:nil].firstObject;
        actionView.frame = CGRectMake(0, self.delegateViewController.navigationController.view.height - actionView.height, self.delegateViewController.navigationController.view.width, actionView.height);

        DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.delegateViewController.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

        __weak typeof(popoverView) weakPopover = popoverView;
        [actionView.cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];

        __weak typeof(self) weakSelf = self;
        [actionView.shareButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [MobClick event:@"105"];
                [weakSelf.delegate detailHeaderView:weakSelf didSelectShareAlbum:weakSelf.album];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
        [popoverView displayAnimated:YES completion:nil];
    }
    else
    {
        PPFriendsTimelineCellMoreActionSheet *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPFriendsTimelineCellMoreActionSheet" owner:nil options:nil].firstObject;
        actionView.frame = CGRectMake(0, self.delegateViewController.navigationController.view.height - actionView.height, self.delegateViewController.navigationController.view.width, actionView.height);

        DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.delegateViewController.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

        __weak typeof(self) weakSelf = self;
        __weak typeof(popoverView) weakPopover = popoverView;
        [actionView.cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.shareButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [MobClick event:@"105"];
                [weakSelf.delegate detailHeaderView:weakSelf didSelectShareAlbum:weakSelf.album];
            }];
        } forControlEvents:UIControlEventTouchUpInside];

        [actionView.complainButton setActionBlock:^(UIControl *control) {
            //投诉
            [weakPopover dismissAnimated:YES completion:^{
                [MobClick event:@"106"];
                PPComplainViewController *vc = [[UIStoryboard storyboardWithName:@"Setting" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"PPComplainViewController"];
                vc.type = @1;
                vc.relationID = weakSelf.album.albumID;
                [weakSelf.delegateViewController.navigationController pushViewController:vc animated:YES];
            }];
            
        } forControlEvents:UIControlEventTouchUpInside];
        [popoverView displayAnimated:YES completion:nil];
    }
}

- (IBAction)likeButtonDidPress:(id)sender {
    if(_likeButton.selected == YES) {
        [MobClick event:@"109"];
        _likeButton.selected = NO;
        _album.like --;
        _album.isLiked = NO;

        [[PPActivityCommitManager sharedInstance] offlineUnlikeAlbumWithAlbumID:_album.albumID.integerValue];
    } else {
        [MobClick event:@"108"];
        _likeButton.selected = YES;
        _album.like ++;
        _album.isLiked = YES;

        [[PPActivityCommitManager sharedInstance] offlineLikeAlbumWithAlbumID:_album.albumID.integerValue];
    }
    [_likeCountButton setTitle:[NSString stringWithFormat:@"%ld", _album.like] forState:UIControlStateNormal];
    [_likeCountButton2 setTitle:[NSString stringWithFormat:@"%ld", _album.like] forState:UIControlStateNormal];
    _likeCountButton2.hidden = (_album.like > 0 && _favouriteCountButton.hidden == YES) ? NO  : YES;
    _likeCountButton.hidden = (_album.like > 0 && _likeCountButton2.hidden == YES) ? NO  : YES;
}

- (IBAction)commentButtonDidPress:(id)sender {
    [MobClick event:@"110"];
    [_delegate detailHeaderView:self didSelectCommentListForAlbum:_album];
}

- (IBAction)favouriteButtonDidPress:(id)sender {

    if(_favouriteButton.selected == YES) {
        [MobClick event:@"112"];
        [[PPActivityCommitManager sharedInstance] offlineUnfavoriteAlbumWithAlbumID:_album.albumID.integerValue];
        _favouriteButton.selected = NO;
        _album.favorite --;
        _album.isFavorited = NO;
    } else {
        [MobClick event:@"111"];
        [[PPActivityCommitManager sharedInstance] offlineFavoriteAlbumWithAlbumID:_album.albumID.integerValue];
        _favouriteButton.selected = YES;
        _album.favorite ++;
        _album.isFavorited = YES;
    }

    [_favouriteCountButton setTitle:[NSString stringWithFormat:@"%ld", _album.favorite] forState:UIControlStateNormal];
    _favouriteCountButton.hidden = _album.favorite > 0 ? NO : YES;
    _likeCountButton2.hidden = (_album.like > 0 && _favouriteCountButton.hidden == YES) ? NO  : YES;
    _likeCountButton.hidden = (_album.like > 0 && _likeCountButton2.hidden == YES) ? NO  : YES;

}

- (IBAction)likeCountButtonDidPress:(id)sender {

    PPTimelineLikesViewController *vc = [[PPTimelineLikesViewController alloc] init];
    vc.type = @1;
    vc.ID = _album.albumID;
    [_delegateViewController.navigationController pushViewController:vc animated:YES];
}

- (IBAction)favouriteCountButtonDidPress:(id)sender {

    PPTimelineFavouritesViewController *vc = [[PPTimelineFavouritesViewController alloc] init];
    vc.albumID = _album.albumID;
    [_delegateViewController.navigationController pushViewController:vc animated:YES];
}

+ (NSDictionary *)attributes
{
    static NSDictionary *attributes;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.maximumLineHeight = paragraph.minimumLineHeight = 22;
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        paragraph.alignment = NSTextAlignmentLeft;

        attributes = @{NSParagraphStyleAttributeName: paragraph, NSForegroundColorAttributeName: [UIColor colorWithRGBHex:0x4d4d4d], NSFontAttributeName: [UIFont systemFontOfSize:15]};
    });
    return attributes;
}

+ (CGFloat)heightForAlbum:(PPAlbumObject *)album
{
    CGFloat height = 0;

    height += 46;
    height += [UIScreen mainScreen].bounds.size.width;

    NSString *description = album.desc;

    if ([description length] == 0)
    {
        height += 0;
    }
    else
    {
        height += 8;

        CGSize constrainedSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 2*15, CGFLOAT_MAX);

        CGSize descSize = [description boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine attributes:[self class].attributes context:nil].size;

        height += descSize.height;
    }

    height += 42;
    
    return (NSInteger)round(height);
}

@end
